package com.example.coursehub.service.impl;

import com.example.coursehub.entity.*;
import com.example.coursehub.repository.ChapterRepository;
import com.example.coursehub.repository.CourseRepository;
import com.example.coursehub.repository.CourseStudentRepository;
import com.example.coursehub.repository.StudentChapterRepository;
import com.example.coursehub.service.ChapterService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ChapterServiceImpl implements ChapterService {

    private final ChapterRepository chapterRepository;
    private final StudentChapterRepository studentChapterRepository;
    private final CourseRepository courseRepository;
    private final CourseStudentRepository courseStudentRepository;

    public ChapterServiceImpl(ChapterRepository chapterRepository, StudentChapterRepository studentChapterRepository, CourseRepository courseRepository, CourseStudentRepository courseStudentRepository) {
        this.chapterRepository = chapterRepository;
        this.studentChapterRepository = studentChapterRepository;
        this.courseRepository = courseRepository;
        this.courseStudentRepository = courseStudentRepository;
    }

    @Override
    public Chapter createChapter(Chapter chapter) {
        // 保存章节
        Chapter savedChapter = chapterRepository.save(chapter);

        // 获取课程ID
        String courseId = savedChapter.getCourse().getCourseId();
//        System.out.println("看看这里"+courseId);
        // 查询该课程下的所有学生
        List<CourseStudent> courseStudents = courseStudentRepository.findByCourse_CourseId(courseId);
//        System.out.println("看看这里"+courseStudents);
        // 为每个学生创建初始学习记录（默认为未完成状态）
        courseStudents.forEach(courseStudent -> {
            StudentChapterId studentChapterId = new StudentChapterId();
            studentChapterId.setUserId(courseStudent.getUser().getUserId());
            studentChapterId.setChapterId(savedChapter.getChapterId());

            StudentChapter studentChapter = new StudentChapter();
            studentChapter.setId(studentChapterId);
            studentChapter.setUser(courseStudent.getUser());
            studentChapter.setChapter(savedChapter);
            studentChapter.setIsFinished(false); // 默认未完成

            studentChapterRepository.save(studentChapter);
        });

        return savedChapter;
    }

    @Override
    public Chapter updateChapter(String chapterId, Chapter updatedChapter) {
        Optional<Chapter> optionalChapter = chapterRepository.findById(chapterId);
        if (optionalChapter.isPresent()) {
            Chapter chapter = optionalChapter.get();
            chapter.setChapterName(updatedChapter.getChapterName());
            chapter.setCourse(updatedChapter.getCourse());
            return chapterRepository.save(chapter);
        }
        throw new RuntimeException("Chapter not found with id: " + chapterId);
    }

    @Override
    public void deleteChapter(String chapterId) {
        chapterRepository.deleteById(chapterId);
    }

    @Override
    public Chapter getChapterById(String chapterId) {
        return chapterRepository.findById(chapterId)
                .orElseThrow(() -> new RuntimeException("Chapter not found with id: " + chapterId));
    }

    @Override
    public List<Chapter> getChaptersByCourseId(String courseId) {
        return chapterRepository.findByCourse_CourseId(courseId);
    }

    @Override
    public List<Chapter> getAllChapters() {
        return chapterRepository.findAll();
    }

    @Override
    public List<Chapter> getLearnedChaptersByStudent(String userId, String courseId) {
        // 查询学生已完成的章节关系
        List<StudentChapter> studentChapters = studentChapterRepository
                .findByUser_UserIdAndChapter_Course_CourseIdAndIsFinished(userId, courseId, true);

        // 提取章节ID
        List<String> chapterIds = studentChapters.stream()
                .map(sc -> sc.getChapter().getChapterId())
                .collect(Collectors.toList());

        // 根据章节ID列表查询章节信息
        return chapterRepository.findAllById(chapterIds);
    }

    @Override
    public void markChapterAsFinished(String userId, String chapterId) {
        // 验证章节存在
        Chapter chapter = chapterRepository.findById(chapterId)
                .orElseThrow(() -> new RuntimeException("Chapter not found with id: " + chapterId));

        // 构建复合主键
        StudentChapterId id = new StudentChapterId();
        id.setUserId(userId);
        id.setChapterId(chapterId);

        // 查询或创建学习记录
        StudentChapter studentChapter = studentChapterRepository.findById(id)
                .orElseGet(() -> {
                    StudentChapter sc = new StudentChapter();
                    sc.setId(id);
                    sc.setUser(new User(userId));
                    sc.setChapter(chapter);
                    return sc;
                });

        // 更新状态为已完成
        studentChapter.setIsFinished(true);
        studentChapterRepository.save(studentChapter);
    }
}